import React, { Component } from 'react'
import { StatusBar, Alert, BackHandler, ScrollView, Text, KeyboardAvoidingView } from 'react-native'
import { Button, TextInput } from '../Components'
import { connect } from 'react-redux'
import UserActions from '../Redux/UserRedux'

// Styles
import styles from './Styles/UserUpdateScreenStyle'

class UserUpdateScreen extends Component {
  static navigationOptions = ({navigation}) => ({
    title: navigation.state.params.title
  })
  constructor(props) {
    super(props)
    const { state } = this.props.navigation
    const field = state.params.field
    this.state = {
      field: field,
      value: this.props.user.payload[field]
    }
  }
  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  componentDidUpdate(prevProps, prevState) {
    if(prevProps.user.fetching
      && !this.props.user.fetching
      && !this.props.user.error) {
      this.props.navigation.goBack()
    }
    if(prevProps.user.fetching 
      && !this.props.user.fetching 
      && this.props.user.error) {
      Alert.alert('保存失败')
    }
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  _onPress = () => {
    if(this.state.value) {
      return this.props.update(
        this.props.user.payload.token,
        this.state.field,
        this.state.value
      )
    }
    Alert.alert('请输入完整信息')
  }
  render () {
    return (
      <ScrollView style={styles.container}>
        <StatusBar translucent={false} barStyle='dark-content' backgroundColor='white' />
        <KeyboardAvoidingView behavior='position'>
          <TextInput autoFocus
            onChangeText={(value) => this.setState({value:value})}
            value={this.state.value} />
          {this.props.user.fetching ? (
            <Button title='保存中...' disabled />
          ) : (
            <Button title='保存' onPress={this._onPress} />
          )}
        </KeyboardAvoidingView>
      </ScrollView>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    update: (token,field,value) => dispatch(UserActions.updateUserRequest(token, field, value))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(UserUpdateScreen)
